﻿using Hx.ADSyncPlatform.Common.Config;
using Hx.ADSyncPlatform.Controllers.Base;
using Hx.ADSyncPlatform.Entity.Entities;
using Hx.ADSyncPlatform.Infrastructure.Expression.Common;
using Hx.ADSyncPlatform.Infrastructure.Tree;
using Hx.ADSyncPlatform.Service;
using Hx.ADSyncPlatform.WebApi.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Hx.ADSyncPlatform.Controllers
{
    /// <summary>
    /// 权限
    /// </summary>
    [Route("api/plat/permission")]
    [Authorize]

    [ApiController]
    public class Plat_SysPermissionController : BaseController
    {
        private Plat_SysManagerService plat_SysManagerService;
        private Plat_SysRoleService plat_SysRoleService;
        private Plat_SysPermissionService plat_SysPermissionService;
        private DefaultRole defaultRole;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="plat_SysPermissionService"></param>
        public Plat_SysPermissionController(Plat_SysManagerService plat_SysManagerService,
            Plat_SysPermissionService plat_SysPermissionService, Plat_SysRoleService plat_SysRoleService,
            IOptions<DefaultRole> defaultRoleAccessor,
            IServiceProvider serviceProvider) : base(serviceProvider)
        {
            this.plat_SysManagerService = plat_SysManagerService;
            this.plat_SysPermissionService = plat_SysPermissionService;
            this.plat_SysRoleService = plat_SysRoleService;
            this.defaultRole = defaultRoleAccessor.Value;


        }

        /// <summary>
        ///  获取用户权限列表 前端生成路由使用
        /// </summary>
        /// <returns></returns>
        [HttpGet("tree")]
        public async Task<Result<Dictionary<string, IList>>> GetPermissionTree()
        {
            Guid managerId = platManager.ManagerId;
            Plat_SysManager plat_manager = null;
            List<Plat_SysPermission> list = new List<Plat_SysPermission>();
            List<Plat_SysRole> plat_SysRoles = new List<Plat_SysRole>();
            string loginType = platManager.LoginType;
            if (loginType == "sso")
            {
                plat_manager = await plat_SysManagerService.Single(n => n.ObjectGuid == managerId);
            }
            else
            {
                plat_manager = await plat_SysManagerService.Single(n => n.UserId == managerId);
            }

            if (plat_manager == null)//ad用户
            {
                list = await plat_SysPermissionService.GetPermissionsByRoleId(new Guid(defaultRole.Id));
                plat_SysRoles.Add(await plat_SysRoleService.QueryById(defaultRole.Id));
            }
            else//平台管理员
            {
                list = await plat_SysPermissionService.GetPermissionsByUserId(plat_manager.UserId);
                plat_SysRoles = plat_SysRoleService.GetRolesByUserId(plat_manager.UserId);
            }
            var allMenus = await plat_SysPermissionService.Query(n => n.type == 2 && n.IsEnable == 1, "sort_order asc");


            var permissionTreeViews = list.Select(n => new PermissionTreeViewModel()
            {
                Id = n.PermissionId,
                ParentId = n.ParentId,
                Path = n.path,
                Component = n.Component,
                Code = n.Code,
                Icon = n.Icon,
                Name = n.Name,
                Type = n.type,
                title = n.DisplayName,
                visible = n.visible == 1,
                sort = n.sort_order
            });
            Dictionary<string, IList> result = new Dictionary<string, IList>();

            var permissionTreeList = TreeHelper<PermissionTreeViewModel>
                .BulidTree(permissionTreeViews.Where(n => n.Type != 3), Guid.Empty);

            result.Add("allMenus", allMenus);

            result.Add("menus", permissionTreeList);

            result.Add("roles", plat_SysRoles.Select(n => n.RoleCode).ToList());

            var btnList = list.Where(n => n.type == 3).ToList();
            result.Add("btns", btnList);


            return await base.Success<Dictionary<string, IList>>(result);
        }


        #region 权限管理


        /// <summary>
        /// 角色分配权限 下拉数据源
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        //[Authorize(policy: "privilege")]
        [HttpGet("menuTree")]
        public async Task<Result<Dictionary<string, IList>>> GetMenuTree(Guid roleId)
        {
            var permissions = await plat_SysPermissionService.Query(n => n.IsEnable == 1, "sort_order asc");
            var permissionTreeViews = permissions.Select(n => new PermissionTreeViewModel()
            {
                Id = n.PermissionId,
                ParentId = n.ParentId,
                Path = n.path,
                Component = n.Component,
                Code = n.Code,
                Icon = n.Icon,
                Name = n.Name,
                Type = n.type,
                title = n.DisplayName,
                visible = n.visible == 1
            });
            var permissionTreeList = TreeHelper<PermissionTreeViewModel>
              .BulidTree(permissionTreeViews, Guid.Empty);
            Dictionary<string, IList> result = new Dictionary<string, IList>();
            result.Add("menus", permissionTreeList.ToList());
            if (roleId != Guid.Empty)
            {
                var ownedList = await plat_SysPermissionService.GetPermissionsByRoleId(roleId);
                var ownedIds = ownedList.Select(n => n.PermissionId).ToList();
                result.Add("checkedKeys", ownedIds);
            }

            return await base.Success<Dictionary<string, IList>>(result);
        }




        //[Authorize(policy: "privilege")]
        /// <summary>
        /// 权限列表 
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpGet("list")]
        public async Task<Result<List<Plat_SysPermission>>> GetPermissionList([FromQuery] Dictionary<string, string> query)
        {

            Expression<Func<Plat_SysPermission, bool>> where = n => true;
            if (query.ContainsKey("displayName"))
            {
                where = where.And(n => n.DisplayName.Contains(query["displayName"].ToString()));
            }
            if (query.ContainsKey("isEnable"))
            {
                where = where.And(n => n.IsEnable == int.Parse(query["isEnable"].ToString()));
            }
            var permissions = await plat_SysPermissionService.Query(where, "sort_order asc");

            var permissionTreeList = TreeHelper<Plat_SysPermission>.BulidTree(permissions, Guid.Empty);
            return await base.Success<List<Plat_SysPermission>>(permissionTreeList);

        }

        //[Authorize(policy: "privilege")]
        /// <summary>
        /// 权限
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpGet("{id}")]
        public async Task<Result<Plat_SysPermission>> GetPermission([FromRoute] Guid id)
        {
            var permission = await plat_SysPermissionService.Single(n => n.PermissionId == id);
            return await base.Success<Plat_SysPermission>(permission);

        }

        //[Authorize(policy: "privilege")]
        /// <summary>
        /// 添加权限
        /// </summary>
        ///<param name="plat_SysPermission"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<Result> AddPermission([FromBody] Plat_SysPermission plat_SysPermission)
        {
            plat_SysPermission.Id = Guid.NewGuid();
            await plat_SysPermissionService.Add(plat_SysPermission);
            logHelper.WriteToDb(BehaviorType.Operation, $"用户【{platManager.Name}】创建了系统权限【{plat_SysPermission.DisplayName}】");
            return await base.Success();

        }



        //[Authorize(policy: "privilege")]
        /// <summary>
        /// 修改权限
        /// </summary>
        ///<param name="plat_SysPermission"></param>
        /// <returns></returns>
        [HttpPost("edit")]
        public async Task<Result> EditPermission([FromBody] Plat_SysPermission plat_SysPermission)
        {
            await plat_SysPermissionService.Update(plat_SysPermission);
            logHelper.WriteToDb(BehaviorType.Operation, $"用户【{platManager.Name}】修改了系统权限，权限id为【{plat_SysPermission.PermissionId}】 ");

            return await base.Success();
        }

        //[Authorize(policy: "privilege")]
        /// <summary>
        /// 删除权限
        /// </summary>
        ///<param name="id"></param>
        /// <returns></returns>
        //[Authorize(policy: "privilege")]
        [HttpDelete("delete/{id}")]
        public async Task<Result> DeletePermission([FromRoute] Guid id)
        {
            await plat_SysPermissionService.DeletePermission(id);
            logHelper.WriteToDb(BehaviorType.Operation, $"用户【{platManager.Name}】删除了系统权限，权限id为【{id}】 ");
            return await base.Success();
        }

        #endregion

    }
}
